package com.example.delicioushunter.view.activity;

import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.example.delicioushunter.R;
import com.example.delicioushunter.control.databasecontrol.MaterialControl;
import com.example.delicioushunter.control.databasecontrol.MaterialsInFoodControl;
import com.example.delicioushunter.model.database.DHDatabaseHelper;
import com.example.delicioushunter.model.object.Material;
import com.example.delicioushunter.model.object.MaterialsInFood;
import com.example.delicioushunter.view.adapter.MaterialAdapter;
import com.example.delicioushunter.view.adapter.MaterialOnFoodAdapter;

public class MaterialFragment extends Fragment {

	private ImageView imgCancel, imgSave;
	private EditText editMaterialContent;
	private RelativeLayout layoutAdd;
	private ListView listMaterials;
	private Gallery galleryMaterial;
	private Context mContext;
	private ArrayList<Material> materials;
	private ArrayList<String> materials_on_food;
	private ArrayList<MaterialsInFood> list;
	private MaterialOnFoodAdapter listadapter;
	private MaterialAdapter adapter;
	private DHDatabaseHelper helper;
	private SQLiteDatabase rdb;
	private SQLiteDatabase wdb;
	private MaterialControl control;
	private View rootView;
	private ArrayList<Integer> mychoices;
	private int selected = 0;
	private boolean isLoad = false;
	private Uri picUri;
	private int _id;

	private RelativeLayout frame01, layoutMaterial;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mContext = getActivity();
		rootView = inflater.inflate(R.layout.fragment_material, container,
				false);

		editMaterialContent = (EditText) rootView
				.findViewById(R.id.editMaterialContent);
		imgCancel = (ImageView) rootView.findViewById(R.id.imgCancel);
		imgSave = (ImageView) rootView.findViewById(R.id.imgSave);
		imgCancel.setOnTouchListener(imgCancelTouch);
		imgSave.setOnTouchListener(imgSaveTouch);

		layoutAdd = (RelativeLayout) rootView.findViewById(R.id.layoutAdd);
		frame01 = (RelativeLayout) rootView.findViewById(R.id.frame01);
		layoutMaterial = (RelativeLayout) rootView
				.findViewById(R.id.layoutMaterial);

		layoutAdd.setVisibility(View.GONE);
		frame01.setVisibility(View.GONE);
		layoutMaterial.setVisibility(View.GONE);

		listMaterials = (ListView) rootView.findViewById(R.id.listMaterials);
		galleryMaterial = (Gallery) rootView.findViewById(R.id.galleryMaterial);
		materials_on_food = new ArrayList<String>();
		list = new ArrayList<MaterialsInFood>();
		listadapter = new MaterialOnFoodAdapter(mContext, materials_on_food);
		materials = new ArrayList<Material>();
		mychoices = new ArrayList<Integer>();
		adapter = new MaterialAdapter(mContext, materials);

		listMaterials.setAdapter(listadapter);
		galleryMaterial.setAdapter(adapter);
		listMaterials.setOnItemClickListener(mOnItemListClick);
		listMaterials.setOnItemLongClickListener(mOnItemLongClick);
		galleryMaterial.setOnItemClickListener(mOnItemClick);

		Intent intent = getActivity().getIntent();
		_id = Integer.parseInt(intent.getExtras().getString("ID"));
		helper = new DHDatabaseHelper(mContext);

		loadMaterialsOnFood();
		setHasOptionsMenu(true);
		Log.d("Life", "Materials - onCreate");
		return rootView;
	}

	private OnTouchListener imgCancelTouch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			editMaterialContent.setText(null);
			layoutAdd.setVisibility(View.GONE);
			return false;
		}
	};

	private OnTouchListener imgSaveTouch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			String input = editMaterialContent.getText().toString();
			materials_on_food.set(selected, input);
			MaterialsInFood m = list.get(selected);
			m.setDescription(input);
			list.set(selected, m);
			layoutAdd.setVisibility(View.GONE);
			listadapter.notifyDataSetChanged();
			return false;
		}
	};

	private OnItemClickListener mOnItemListClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View v, int position,
				long id) {
			selected = position;
			layoutAdd.setVisibility(View.VISIBLE);
			editMaterialContent.setText(materials_on_food.get(position));
		}
	};

	private OnItemLongClickListener mOnItemLongClick = new OnItemLongClickListener() {

		@Override
		public boolean onItemLongClick(AdapterView<?> parent, View v,
				int position, long id) {
			
			if (list.get(position).get_id() > 0) {
				Log.d("Check", "Delete old " + list.get(position).get_id());
				wdb = helper.getWritableDatabase();
				MaterialsInFoodControl control = new MaterialsInFoodControl();
				control.deleteMaterialonFood(list.get(position).get_id(), wdb);
			}
			list.remove(position);
			mychoices.remove(position);
			materials_on_food.remove(position);
			listadapter.notifyDataSetChanged();
			adapter.notifyDataSetChanged();
			return true;
		}
	};

	private OnItemClickListener mOnItemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View v, int position,
				long id) {
			mychoices.add(materials.get(position).get_id());
			materials_on_food.add(" 1/2 cup of "
					+ materials.get(position).getName());
			MaterialsInFood m = new MaterialsInFood();
			m.setFood_id(_id);
			m.setMaterial_id(materials.get(position).get_id());
			m.setDescription(" 1/2 cup of " + materials.get(position).getName());
			list.add(m);
			materials.remove(position);
			listadapter.notifyDataSetChanged();
			adapter.notifyDataSetChanged();
		}
	};

	private void loadMaterialsOnFood() {
		MaterialsInFoodControl control = new MaterialsInFoodControl();
		rdb = helper.getReadableDatabase();
		list.clear();
		ArrayList<MaterialsInFood> mylist = control.getAllMaterialsInFood(rdb,
				_id);
		for (MaterialsInFood m : mylist) {
			list.add(m);
			mychoices.add(m.getMaterial_id());
			materials_on_food.add(m.getDescription());
			listadapter.notifyDataSetChanged();
		}
	}

	private void loadMaterials() {
		LoadMaterialsTask task = new LoadMaterialsTask();
		task.execute();
	}

	private class LoadMaterialsTask extends
			AsyncTask<Void, Void, ArrayList<Material>> {

		private ProgressDialog pd;

		@Override
		protected ArrayList<Material> doInBackground(Void... params) {
			try {
				rdb = helper.getReadableDatabase();
				control = new MaterialControl();
				return control.getAllMaterials(rdb);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(ArrayList<Material> result) {
			super.onPostExecute(result);
			materials.clear();
			for (Material m : result) {
				addMaterial(m);
			}

			result.clear();
			pd.dismiss();
		}

		@Override
		protected void onPreExecute() {
			pd = new ProgressDialog(mContext, R.style.MyDialogTheme);
			pd.setMessage("Loading...");
			pd.show();
		}

	}

	private void addMaterial(Material m) {
		materials.add(0, m);
		adapter.notifyDataSetChanged();
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// TODO Auto-generated method stub
		inflater.inflate(R.menu.control_materials, menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_import:
			importMaterial();
			break;

		case R.id.action_save:
			addMaterialsInFood();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void importMaterial() {
		if (frame01.getVisibility() == View.GONE)
			frame01.setVisibility(View.VISIBLE);
		else
			frame01.setVisibility(View.GONE);
		if (layoutMaterial.getVisibility() == View.GONE) {
			layoutMaterial.setVisibility(View.VISIBLE);
			if (!isLoad) {
				loadMaterials();
				isLoad = true;
			}
		} else
			layoutMaterial.setVisibility(View.GONE);
	}

	private void addMaterialsInFood() {
		MaterialsInFoodControl control = new MaterialsInFoodControl();

		ArrayList<MaterialsInFood> newMaterials = new ArrayList<MaterialsInFood>();
		ArrayList<MaterialsInFood> oldMaterials = new ArrayList<MaterialsInFood>();
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).get_id() == 0)
				newMaterials.add(list.get(i));
			else
				oldMaterials.add(list.get(i));
		}
		wdb = helper.getReadableDatabase();
		control.addMaterialsInFood(newMaterials, wdb);
		wdb = helper.getReadableDatabase();
		control.updateAllMaterialsInFood(oldMaterials, wdb);
		Toast.makeText(mContext, "Update Successfully", Toast.LENGTH_SHORT)
				.show();
	}

}
